

package com.zdsx.exception;

import com.zdsx.common.exception.ErrorCode;
import com.zdsx.common.exception.CommonException;
import com.zdsx.common.utils.MessageUtils;
import com.zdsx.common.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static com.zdsx.common.exception.ErrorCode.PARAMETER_ERROR;

/**
 * 异常处理器
 *
 * @author Lr
 * @since 1.0.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(CommonException.class)
	public Result handleRenException(CommonException ex){
		Result result = new Result();
		result.error(ex.getCode(), ex.getMsg());

		return result;
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public Result handleDuplicateKeyException(DuplicateKeyException ex){
		Result result = new Result();
		result.error(ErrorCode.DB_RECORD_EXISTS);

		return result;
	}

	@ExceptionHandler(Exception.class)
	public Result handleException(Exception ex){
		logger.error(ex.getMessage(), ex);

		return new Result().error();
	}


	@ExceptionHandler(value = {MethodArgumentNotValidException.class}) // BindException.class, ValidationException.class,
	public Result handleValidationExceptions(MethodArgumentNotValidException ex) {
		FieldError firstError = ex.getBindingResult().getFieldError();
		String key = firstError.getDefaultMessage();
		String fieldName = firstError.getField();
		String message = MessageUtils.getMessage(PARAMETER_ERROR, fieldName);
//		return new Result().error(PARAMETER_ERROR, String.format("{%s}%s", fieldName, message));
		return new Result().error(PARAMETER_ERROR, key);
	}
}